package com.kensure.shike.user.service;

import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import co.kensure.frame.JSBaseService;
import co.kensure.mem.CollectionUtils;
import co.kensure.mem.DateUtils;
import co.kensure.mem.MapUtils;

import com.kensure.basekey.BaseKeyService;
import com.kensure.shike.user.dao.SKUserVipDao;
import com.kensure.shike.user.model.SKUser;
import com.kensure.shike.user.model.SKUserVip;

/**
 * 用户vip有效期服务实现类
 * 
 * @author fankd created on 2019-6-24
 * @since
 */
@Service
public class SKUserVipService extends JSBaseService {

	@Resource
	private SKUserVipDao dao;
	@Resource
	private BaseKeyService baseKeyService;
	@Resource
	private SKUserService sKUserService;

	public SKUserVip selectOne(Long id) {
		return dao.selectOne(id);
	}

	public List<SKUserVip> selectByIds(Collection<Long> ids) {
		return dao.selectByIds(ids);
	}

	public List<SKUserVip> selectAll() {
		return dao.selectAll();
	}

	public List<SKUserVip> selectByWhere(Map<String, Object> parameters) {
		return dao.selectByWhere(parameters);
	}

	public long selectCount() {
		return dao.selectCount();
	}

	public long selectCountByWhere(Map<String, Object> parameters) {
		return dao.selectCountByWhere(parameters);
	}

	public boolean insert(SKUserVip obj) {
		super.beforeInsert(obj);
		obj.setId(baseKeyService.getKey("sk_user_vip"));
		return dao.insert(obj);
	}

	public boolean update(SKUserVip obj) {
		return dao.update(obj);
	}

	public boolean updateByMap(Map<String, Object> params) {
		return dao.updateByMap(params);
	}

	public SKUserVip getUserVip() {
		SKUser user = sKUserService.getUser();
		SKUserVip vip = getUserVip(user.getId());
		return vip;
	}

	public SKUserVip getUserVip(Long userid) {
		SKUser user = sKUserService.selectOne(userid);
		SKUserVip vip = null;
		if (user != null) {
			Map<String, Object> parameters = MapUtils.genMap("userid", user.getId(), "status", 1, "orderby", "time_expire desc");
			List<SKUserVip> list = selectByWhere(parameters);
			if (CollectionUtils.isNotEmpty(list)) {
				vip = list.get(0);
			}
		}
		return vip;
	}

	/**
	 * 会员有效期延长
	 * 
	 * @param userid
	 */
	public SKUserVip add(long userid) {
		SKUserVip vip = new SKUserVip();
		vip.setUserid(userid);
		vip.setStatus(1);
		Date timeStart = new Date();
		Date timeExpire = DateUtils.getPastMonth(timeStart, 12);
		vip.setTimeStart(timeStart);
		vip.setTimeExpire(timeExpire);
		insert(vip);
		return vip;
	}

}
